package com.example.javademo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

public class NetworkUtils {
    public interface NetworkCallback {
        void onSuccess(String response);
        void onError(Exception e);
    }

    public static void makeGetRequest(String urlString, NetworkCallback callback) {
        new Thread(() -> {
            try {
                URL url = new URL(urlString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();
                connection.setRequestMethod("GET");
                connection.setConnectTimeout(5000);
                connection.connect();

                int code = connection.getResponseCode();
                if (code == HttpURLConnection.HTTP_OK) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                    );
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    callback.onSuccess(response.toString());
                } else {
                    callback.onError(new Exception("HTTP Error: " + code));
                }
            } catch (Exception e) {
                callback.onError(e);
            }
        }).start();
    }


    public static void makePostRequest(String urlString, java.util.Map<String, String> formData, NetworkCallback callback) {
        new Thread(() -> {
            try {
                URL url = new URL(urlString);
                HttpURLConnection connection = (HttpURLConnection) url.openConnection();

                connection.setRequestMethod("POST");
                connection.setConnectTimeout(5000);

                // 设置表单数据请求头
                connection.setRequestProperty("Content-Type", "application/x-www-form-urlencoded");

                connection.setDoOutput(true);

                // 构建表单数据
                StringBuilder formBody = new StringBuilder();
                if (formData != null && !formData.isEmpty()) {
                    boolean first = true;
                    for (java.util.Map.Entry<String, String> entry : formData.entrySet()) {
                        if (!first) {
                            formBody.append("&");
                        }
                        formBody.append(URLEncoder.encode(entry.getKey(), "UTF-8"))
                        .append("=")
                        .append(URLEncoder.encode(entry.getValue(), "UTF-8"));
                        first = false;
                    }
                }

                // 发送表单数据
                try (OutputStream os = connection.getOutputStream()) {
                    byte[] input = formBody.toString().getBytes("UTF-8");
                    os.write(input, 0, input.length);
                }

                int code = connection.getResponseCode();
                if (code == HttpURLConnection.HTTP_OK || code == HttpURLConnection.HTTP_CREATED) {
                    BufferedReader reader = new BufferedReader(
                            new InputStreamReader(connection.getInputStream())
                    );
                    StringBuilder response = new StringBuilder();
                    String line;
                    while ((line = reader.readLine()) != null) {
                        response.append(line);
                    }
                    reader.close();
                    callback.onSuccess(response.toString());
                } else {
                    callback.onError(new Exception("HTTP Error: " + code));
                }
            } catch (Exception e) {
                callback.onError(e);
            }
        }).start();
    }

}
